package com.example.demo03.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.example.demo03.entity.response.ErrorResponse;


/**
 * GlobalExceptionHandler class is used to handle exceptions across the whole
 * application. It uses @ControllerAdvice to intercept and handle exceptions
 * thrown from different controllers.
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * Handle the runtime exception RuntimeException. This method will be invoked
     * when a RuntimeException is thrown. It will return an ErrorResponse with HTTP
     * status code 500 and the error message from the exception.
     *
     * @param ex The RuntimeException instance.
     * @return ErrorResponse with status code 500 and error message.
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorResponse handleRuntimeException(RuntimeException ex) {
        log.error("RuntimeException occurred: ", ex);
        return new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
    }


    /**
     * Handle other exceptions Exception. This method will be invoked when an
     * Exception is thrown. It will return an ErrorResponse with HTTP status code
     * 500 and the error message from the exception.
     *
     * @param ex The Exception instance.
     * @return ErrorResponse with status code 500 and error message.
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorResponse handleException(Exception ex) {
        log.error("Exception occurred: ", ex);
        return new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
    }
}